const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const db = require('../db'); // 引入数据库连接

// 获取学生缴费历史
router.get('/payment/history', (req, res) => {
    // 验证token并获取学生信息
    const token = req.headers['authorization'];
    if (!token) {
        return res.status(403).json({ message: "没有提供认证信息" });
    }

    // 解析token获取studentId
    jwt.verify(token, "kio", (err, decoded) => {
        if (err) {
            return res.status(401).json({ message: "认证失败" });
        }

        const studentId = decoded.studentId; // 从token中获取studentId

        // 查询学生的缴费记录
        const sql = 'SELECT * FROM payments WHERE studentId = ? ORDER BY createdAt DESC';
        db.query(sql, [studentId], (err, results) => {
            if (err) {
                return res.status(500).json({ message: '数据库查询失败' });
            }
            res.json(results);
        });
    });
});

// 学生缴费接口
router.post('/payment', (req, res) => {
    const { amount, paymentMethod, cardNumber, paymentPassword } = req.body;
    // 验证token并获取学生信息
    const token = req.headers['authorization'];

    if (!token) {
        return res.status(403).json({ message: "没有提供认证信息" });
    }

    // 解析token获取studentId
    jwt.verify(token, "kio", (err, decoded) => {
        if (err) {
            return res.status(401).json({ message: "认证失败" });
        }

        const studentId = decoded.studentId;
        const paymentStatus = "success"; // 假设支付成功
        const sql = `INSERT INTO payments (studentId, amount, paymentMethod, paymentStatus, cardNumber, paymentPassword) VALUES (?, ?, ?, ?, ?, ?)`;

        db.query(sql, [studentId, amount, paymentMethod, paymentStatus, cardNumber, paymentPassword], (err, results) => {
            if (err) {
                return res.status(500).json({ message: "缴费失败" });
            }

            // 更新学生表中的已缴费金额
            const updateSql = 'UPDATE students SET paidAmount = paidAmount + ? WHERE studentId = ?';
            db.query(updateSql, [amount, studentId], (err, updateResults) => {
                if (err) {
                    return res.status(500).json({ message: "更新学生缴费金额失败" });
                }
                res.json({ message: '缴费成功' });
            });
        });
    });
});

module.exports = router;
